import { observable, computed, action } from 'mobx';

export class LoadHoc {
    @observable public loading: boolean;
    private loadingCode: number;
    @observable public loadingStatus: Object;
    constructor() {
        this.loadingCode = 0;
        this.loadingStatus = {};
    }

    @action.bound
    protected setLoading(key) {
        this.loadingStatus[key] = true;
        this.loadingCode++;
        this.loading = this.loadingCode > 0;
    }

    @action.bound
    protected setLoaded(key) {
        this.loadingStatus[key] = false;
        this.loadingCode--;
        this.loading = this.loadingCode > 0;
    }
}

export const loading = (target, key, descriptor) => {
    let method = descriptor.value;
    descriptor.value = async function () {
        this.setLoading(key);
        const result = await method.apply(this, arguments);
        this.setLoaded(key);
        return result;
    };
}